"""
系统工具相关
"""
from signal import SIGKILL

import psutil


def kill_by_port(port: int):
    """
    杀死占用端口的进程
    查找所有进程，看占用的端口，然后杀死
    :param port:
    :return:
    """
    for proc in psutil.process_iter():
        for conns in proc.connections(kind='inet'):
            if conns.laddr.port == port:
                try:
                    proc.send_signal(SIGKILL)
                except psutil.NoSuchProcess as err:
                    pass


def get_available_space(path: str = "/") -> float:
    """
    获取硬盘可用空间， 单位M
    :param path:
    :return:
    """
    return psutil.disk_usage(path).free / 1024 / 1024


def get_total_memory() -> float:
    """
    获取系统总内存
    :return: MB
    """
    mem = psutil.virtual_memory()
    return mem.total / (1024 * 1024)


def get_system_used_memory() -> float:
    """
    获取系统当前已经使用内存
    :return: MB
    """
    mem = psutil.virtual_memory()
    return mem.used / (1024 * 1024)


def get_used_cpu():
    """
    获取CPU占用率百分比
    """
    return psutil.cpu_percent(1)


def get_cpu_info():
    return f"CPU使用{get_used_cpu()}%"


def get_memory_info() -> str:
    """
    获取内存占用情况
    """
    used = get_used_cpu()
    total = get_total_memory()
    return f"内存占用{round(used / total, 2)}%({round(get_system_used_memory(), 2)}M/{round(get_total_memory(), 2)}M)"


def get_disk_info(path="/") -> str:
    """
    获取硬盘使用情况
    """
    disk_info = psutil.disk_usage(path)
    return f"硬盘使用{disk_info.percent}%({round(disk_info.used / 1024 / 1024 / 1024, 2)}G/{round(disk_info.total / 1024 / 1024 / 1024, 2)}G)"


def get_process_info() -> list:
    """
    获取进程信息
    """
    info = []
    for p in psutil.process_iter():
        command = " ".join(p.cmdline())
        memory_info = p.memory_info()
        data = {
            "pid": p.pid,
            "user": p.username(),
            "ni": p.nice(),
            "command": command if command else p.name(),
            "%cpu": round(p.cpu_percent(), 2),
            "%mem": round(p.memory_percent(), 2),
            "s": p.status(),
            "time+": p.cpu_times()[1],
            "shr": round(memory_info[2] / 1024, 2),
            "virt": round(memory_info[1] / 1024, 2),
            "res": round(memory_info[0] / 1024, 2),
        }
        info.append(data)
    return info


def get_system_info() -> dict:
    """
    获取系统使用情况
    """
    return {
        "cpu": get_cpu_info(),
        "memory": get_memory_info(),
        "disk": get_disk_info(),
        "processes": get_process_info()
    }


if __name__ == '__main__':
    print(get_system_info())
